package com.ihelp.rest.mis.platform.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ihelp.rest.base.hibernate4.BaseHibernateDao;
import com.ihelp.rest.base.po.Page;
import com.ihelp.rest.mis.pojo.Onlinetime;
import com.ihelp.rest.utils.JsonCommon;

@Repository
public class OnlinetimeDao extends BaseHibernateDao<Onlinetime, String>{
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	/**
	 * 推荐年龄上网时长
	 * @param queryCondition
	 * @param start
	 * @param pageSize
	 * @param sort
	 * @param order
	 * @return
	 */
	public Page<Onlinetime> queryOnlinetimePage(Onlinetime queryCondition,int start,int pageSize,String sort, String order){
		StringBuilder hql = new StringBuilder();
		ArrayList<Object> list = new ArrayList<Object>();
		hql.append("from Onlinetime t where 1=1 ");
		if(queryCondition.getAge()!=null){
			hql.append(" and t.age=?");
			list.add(queryCondition.getAge());
		}
		if(StringUtils.isNotBlank(sort))
			hql.append(" order by ").append(sort).append(" ").append(order);
		return this.page(hql.toString(), start, pageSize, (Object[])list.toArray());
	}
	
	
	public long validAge(Onlinetime onlinetime){
		long lRet = 0;
		String sql = "";
		if(StringUtils.isBlank(onlinetime.getId()))
			sql = "select count(id) as l_count from Onlinetime t where t.age="+onlinetime.getAge();
		else
			sql = "select count(id) as l_count from Onlinetime t where t.age="+onlinetime.getAge()+" and t.id<>'"+onlinetime.getId()+"'";
		List<Map<String, Object>> result = this.jdbcTemplate.queryForList(sql);
		for (Map<String, Object> one : result) {
			lRet = Long.valueOf(one.get("l_count").toString());
		}
		return lRet;
	}
	
	@Transactional
	public void dropOnline(String ids) throws Exception {
		try {
			NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(this.jdbcTemplate);
			MapSqlParameterSource parameters = new MapSqlParameterSource();  
			parameters.addValue("list", JsonCommon.idsTosList(ids, ","));
			
			StringBuilder sb = new StringBuilder();
			sb = new StringBuilder("DELETE Onlinetime T WHERE T.ID IN (:list)");
			namedParameterJdbcTemplate.update(sb.toString(), parameters);
		}
		catch (Exception e) {
			throw e;
		}
	}
	
	public Double getSuggestTime(int age){
		return (Double)this.jdbcTemplate.queryForObject("select suggesttime from onlinetime where age = '"+age+"' ", Double.class) ;
	}
	
}
